package com.huawei.obs;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.rds.v3.RdsClient;
import com.huaweicloud.sdk.rds.v3.model.*;
import com.huaweicloud.sdk.rds.v3.region.RdsRegion;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


public class RDSAuditlogUploadOBS {
    static LocalDateTime localDateTime = LocalDateTime.now();
    static String fileName = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).toString();
    public static void main(String[] args) {
        //你需要提供下面这些参数
        String endPoint,ak,sk,areaCode,instanceID,obsName,startTime,endTime;
        int offset,limit;
        //下面是各变量值的获取方式：
        //endPoint获取方式参考：https://developer.huaweicloud.com/endpoint获取对应的endPoint值。注意：endpoint值由很多，要找到OBS下面的endpoint
        endPoint = "endPoint";
        //ak与sk获取方式参考：https://support.huaweicloud.com/iam_faq/iam_01_0618.html
        ak = "ak";
        sk = "sk";
        //区域码获取方式，参考：https://developer.huaweicloud.com/endpoint
        areaCode = "areaCode";
        //instanceID实例ID需要在华为云的RDS实例管理界面中获取实例ID
        instanceID = "instanceID";
        //OBS桶名
        obsName = "obsName";
        //起始查询（格式：2018-08-06T10:41:14+0800）
        startTime = "2022-05-01T10:41:14+0800";
        //终点查询时间（格式：2018-08-06T10:41:14+0800）
        endTime = "2022-05-31T10:41:14+0800";
        //起始查询位置
        offset = 0;
        //一次查询的数量，最多能查询50个
        limit = 50;
        //获取审计日志ID
        List<String> ids = getAuditlogID(ak,sk,areaCode,instanceID,startTime,endTime,offset,limit);
        if(ids.size() != 0){
            List<String> fileLinks = DownloadAuditlog(ak,sk,areaCode,instanceID,ids);
            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);

            InputStream inputStream = null;
            try {
                int num = 0;
                for(String fileLink:fileLinks){
                    num++;
                    inputStream = new URL(fileLink).openStream();
                    String storeDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")).toString();
                    //为待上传的本地文件路径，需要指定到具体的文件名
                    PutObjectRequest request = new PutObjectRequest();
                    //OBS桶名
                    request.setBucketName(obsName);
                    //设置在OBS桶中的存储位置,存储位置可以自行设置，如在OBS桶中无对应文件夹，会自动创建。
                    request.setObjectKey("logs/auditlogs"+storeDate+"/"+fileName+"_"+num);
                    request.setInput(inputStream);
                    obsClient.putObject(request);
                    System.out.println("上传成功");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("该时间段无对应日志！");
        }



    }

    /**
     * 获取审计日志id
     * @param ak
     * @param sk
     * @param areaCode
     * @param instanceID
     * @return
     */
    public static List<String> getAuditlogID(String ak, String sk, String areaCode, String instanceID, String startTime, String endTime, int offset, int limit){
        List<String> ids = new ArrayList();
        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        RdsClient client = RdsClient.newBuilder()
                .withCredential(auth)
                .withRegion(RdsRegion.valueOf(areaCode))
                .build();
        ListAuditlogsRequest request = new ListAuditlogsRequest();
        request.withXLanguage("zh-cn");
        request.withInstanceId(instanceID);
        request.withStartTime(startTime);
        request.withEndTime(endTime);
        request.withOffset(offset);
        request.withLimit(limit);
        try {
            ListAuditlogsResponse response = client.listAuditlogs(request);
            //获取慢日志数量
            int num = response.getAuditlogs().size();
            //将所有查询出来的审计日志id存入fileLinks
            for(int count = 0; count < num; count++){
                ids.add(count,String.valueOf(response.getAuditlogs().get(count).getId()));
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return ids;
    }
    /**
     * 获取审计日志下载链接
     * @param ak
     * @param sk
     * @param areaCode
     * @param instanceID
     * @return
     */
    public static List<String> DownloadAuditlog(String ak, String sk, String areaCode, String instanceID,List<String> ids){
        List<String> fileLinks = new ArrayList<>();
        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        RdsClient client = RdsClient.newBuilder()
                .withCredential(auth)
                .withRegion(RdsRegion.valueOf(areaCode))
                .build();
        ShowAuditlogDownloadLinkRequest request = new ShowAuditlogDownloadLinkRequest();
        request.withInstanceId(instanceID);
        GenerateAuditlogDownloadLinkRequest body = new GenerateAuditlogDownloadLinkRequest();
        body.withIds(ids);
        request.withBody(body);
        try {
            ShowAuditlogDownloadLinkResponse response = client.showAuditlogDownloadLink(request);
            for(int count = 0; count < response.getLinks().size(); count++){
                fileLinks.add(count,response.getLinks().get(count));
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return fileLinks;
    }

}
